<?php

namespace app\controller\factory;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

use app\Auth;
use app\BaseController;
use lc\helpers\Helper;
use app\Request;
use lc\helpers\Response;
use think\captcha\facade\Captcha;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{

    /**
     * 跳转首页
     * @return string
     */
    public function index()
    {

        View::config(['view_path' => dirname($this->app->getRootPath()) . '/']);
        return View::fetch('/dashboard');

    }

    /**
     * 验证码
     */
    public function Captcha()
    {
        return Captcha::create();
    }

    /**
     * 登录
     */

    public function login(Request $request)
    {
//        if (captcha::check($request['captcha'])) {
//            // 验证失败
//            return Response::fail('验证失败');
//        }
        $token = Helper::generateNonceStr();
        $time = time()+7200;

        //校验账号密码
        $adminData = Db::table('xd_system_store_staff')->field('id,avatar,staff_name,account,pwd,roles')->where('account', $request['account'])->find();

        if (empty($adminData)) return Response::fail('未找到账号,请重新输入');

        if (password_verify($request['password'],$adminData['pwd'])) {

            Db::table('xd_system_store_staff')->where('id',$adminData['id'])->update([
                'last_time'=>time(),
                'token'=>$token,
                'expired'=>$time
            ]);

            //登录成功
            return Response::success(
                [
                    'id' => $adminData['id'],
                    'avatar'=>$adminData['avatar'],
                    'staff_name'=>$adminData['staff_name'],
                    'roles'=>$adminData['roles'],
                    'token'=>$token,
                    'expired'=>$time
                ]
            );
        } else {
            return response::fail('密码错误,请重新输入');
        }
    }




    public function adminInfo(Request $request){

        $data = Db::table('xd_system_store_staff')->where('token',$request['token'])->find();

        if(empty($data)){
            return response::fail();
        }

        if($data['roles'] == 0){
            $roles = 'admin';
        }else{
            $roles = 'editor';
        }
        $dataInfo = [
            'avatar'=>$data['avatar'],
            'introduction'=>'',
            'name'=>$data['staff_name'],
            'roles'=>[$roles],
        ];

        return response::success($dataInfo);
    }


    /**
     * 修改密码
     * @return void
     */
    public function updatePassword(Request $request){

        $adminId = Auth::$adminId;
        $admin = Auth::$admin;

        return response::success($admin);

//        //查找盐值
//
//        $update = Db::name('admin')->where('id',$adminId)->update([
//            'password'=>md5($request['password'].$admin->salt),
//            'expired'=>time()
//        ]);
//
//        //
//        if($update != 0){
//            return Response::success();
//        }else{
//            return Response::fail('修改失败');
//        }
    }


    /**
     * 员工数据
     * @return void
     */
    public function staffData(Request $request){

        $admin = Auth::$admin;

        $size = $request['limit'] ?? 15;

        $data = Db::table('xd_system_store_staff')->where('store_id',$admin->store_id)->order('id')->paginate($size);

        return response::success($data);
    }


    /**
     * 员工详细信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function staffDataInfo(Request $request){

        $id = $request['id'];

        $now = date('Y-m-d H:i:s');

        $thirtyDaysAgo = date('Y-m-d H:i:s', strtotime('-30 days', strtotime($now)));

        $query = Db::query("SELECT 
    Date,
    SUM(RecordCountZongjiantime) AS RecordCountZongjiantime,
    SUM(RecordCountPutawayDate) AS RecordCountPutawayDate,
    SUM(RecordCountTerminationDate) AS RecordCountTerminationDate,
    SUM(RecordCountPackDate) AS RecordCountPackDate,
    SUM(RecordCountSorting) AS RecordCountSorting,
    SUM(factoryCount) AS factoryCount
FROM (
    SELECT DATE(zongjiantime) AS Date, 
        COUNT(*) AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE zongjiantime >= ? AND zongjiantime <= ? AND staff_id = {$id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(putaway_date) AS Date, 
        0 AS RecordCountZongjiantime,
        COUNT(*) AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE putaway_date >= ? AND putaway_date <= ? AND staff_id = {$id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(termination_date) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        COUNT(*) AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE termination_date >= ? AND termination_date <= ? AND staff_id = {$id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(pack_date) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        COUNT(*) AS RecordCountPackDate,
        0 AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE pack_date >= ? AND pack_date <= ? AND staff_id = {$id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(create_time) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        COUNT(*) AS RecordCountSorting,
        0 AS factoryCount
    FROM xd_store_order_goodsInfo
    WHERE create_time >= ? AND create_time <= ? AND staff_id = {$id}
    GROUP BY Date
    UNION ALL
    SELECT DATE(factory_time) AS Date, 
        0 AS RecordCountZongjiantime,
        0 AS RecordCountPutawayDate,
        0 AS RecordCountTerminationDate,
        0 AS RecordCountPackDate,
        0 AS RecordCountSorting,
        COUNT(*) AS factoryCount
    FROM xd_store_order
    WHERE factory_time >= ? AND factory_time <= ? AND staff_id = {$id}
    GROUP BY Date
) AS Subquery
GROUP BY Date
ORDER BY Date DESC
", [
            $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now, $thirtyDaysAgo, $now
        ]);

        return Response::success($query);
    }


    /**
     * 首页数据
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function homeData(){

        $admin = Auth::$admin;

        /**
         * 当日分拣
         * 当日入厂
         * 即将入厂
         * 当日总检
         * 当日上架
         * 当日打包
         * 超18H未入厂
         * 超24H未分拣
         * 超72H未分拣
         * 即将超时预警
         * 在厂超4天
         * 在厂超6天
         */
        $todaySroting = Db::table('xd_store_order_goodsInfo')->where('store_id',$admin->store_id)
            ->where('create_time','>=',strtotime(date('Y-m-d 00:00:00')))
            ->where('create_time','<=',strtotime(date('Y-m-d 23:59:59')))
            ->count();
        $todayJoinFactory = Db::table('xd_store_order')
            ->where('store_id',$admin->store_id)
            ->whereBetweenTime('factory_time',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->count();
        $beJoinFactory = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status',0)->count();
        $todayExamine = Db::table('xd_store_order_goodsInfo')->where('store_id',$admin->store_id)
            ->whereBetweenTime('zongjiantime',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->count();
        $todayPutWay = Db::table('xd_store_order_goodsInfo')->where('store_id',$admin->store_id)
            ->whereBetweenTime('putaway_date',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->count();
        $todayPack = Db::table('xd_store_order_goodsInfo')->where('store_id',$admin->store_id)
            ->whereBetweenTime('pack_date',date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59'))
            ->count();
        $notSroting = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status',1)->where('factory_time','<',date('Y-m-d H:i:s',time()-86400))
            ->count();
        $ThreeNotSroting = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status',1)->where('factory_time','<',date('Y-m-d H:i:s',time()-(86400*3)))
            ->count();
        $runOut = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status','<>',6)->where('factory_time','<',date('Y-m-d H:i:s',time()-(86400*7)))
            ->count();
        $fourRunOut = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status','<>',6)->where('factory_time','<',date('Y-m-d H:i:s',time()-(86400*4)))
            ->count();
        $sixRunOut = Db::table('xd_store_order')->where('store_id',$admin->store_id)
            ->where('order_status','<>',6)->where('factory_time','<',date('Y-m-d H:i:s',time()-(86400*6)))
            ->count();

        return response::success([
            'todaySroting'=>$todaySroting,
            'todayJoinFactory'=>$todayJoinFactory,
            'beJoinFactory'=>$beJoinFactory,
            'todayExamine'=>$todayExamine,
            'todayPutWay'=>$todayPutWay,
            'todayPack'=>$todayPack,
            'notSroting'=>$notSroting,
            'ThreeNotSroting'=>$ThreeNotSroting,
            'runOut'=>$runOut,
            'fourRunOut'=>$fourRunOut,
            'sixRunOut'=>$sixRunOut,
        ]);
    }



    /**
     * 退出登录
     * @return void
     */
    public function quitLogin(){

        $adminId = Auth::$adminId;
        Db::name('admin')->where('id',$adminId)->update([
            'expired'=>time()
        ]);

        return Response::success();
    }




}
